"""
# -*- coding: utf-8 -*-
# @Time    : 2023/10/11 15:39
# @Author  : 王摇摆
# @FileName: file2.py
# @Software: PyCharm
# @Blog    ：https://blog.csdn.net/weixin_44943389?type=blog
"""
# 导入必要的库
import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

# 读取数据
data = pd.read_csv('../dataset/train.csv')
print('[数据集加载完毕]')

# 分离特征和目标变量
X = data.drop(columns=['id', 'target'])
y = data['target']

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print('[数据集预处理完成]')

# 定义要搜索的超参数网格
param_grid = {
    'C': [0.1, 1, 10],
    'kernel': ['linear', 'rbf', 'poly'],
    'gamma': [0.001, 0.01, 0.1, 1]
}

# 初始化SVC模型
svm_classifier = SVC(random_state=42)

# 创建GridSearchCV对象
grid_search = GridSearchCV(estimator=svm_classifier, param_grid=param_grid,
                           scoring='accuracy', cv=3, verbose=2, n_jobs=-1)

# 在训练数据上拟合GridSearchCV对象
grid_search.fit(X_train, y_train)

# 获取最佳模型和超参数
best_svm_classifier = grid_search.best_estimator_
best_params = grid_search.best_params_

print(f'最佳超参数：{best_params}')

# 使用最佳模型进行预测
y_pred = best_svm_classifier.predict(X_test)

# 评估模型性能
accuracy = accuracy_score(y_test, y_pred)
print(f'准确率：{accuracy}')
